package com.gitee.poi.plugin.core.handler.data;

import com.gitee.poi.plugin.model.CellModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangxin
 * @time 2018/10/29 11:24
 */
public abstract class AbstractDataProcessor implements HandlerDataAnnotation {

    /**
     * 返回该Object，表名子类已处理该cell的值
     */
    public static final Object NONE_PROCESS = new Object();


    private static final Map<Field, HandlerData> cacheMap = new ConcurrentHashMap<>();

    @Override
    public CellModel process(CellModel cellModel) {
        Field field = cellModel.getField();
        try {
            HandlerData handler = cacheMap.get(field);
            if (handler != null) {
                cellModel = handler.process(cellModel);
            } else {
                handler = getHandlerData(field);
                cacheMap.put(field, handler);
                cellModel = handler.process(cellModel);
            }
            writeCell(cellModel);
            return cellModel;
        } catch (Exception e) {
            throw new RuntimeException(field.getName() + "非法的 Transform ", e);
        }
    }

    protected void writeCell(CellModel cellModel) {
        Object cellValue = cellModel.getValue();
        //如果cellValue是None_Process表明底层已经填写了该cell的值
        if (!cellValue.equals(NONE_PROCESS)) {
            Cell cell = cellModel.getCell();
            CellStyle cellStyle = cellModel.getCellStyle();
            cell.setCellStyle(cellStyle);
            cellModel.getWriteCellValue().setCellValue(cell,cellValue);
        }
    }
    protected abstract HandlerData getHandlerData(Field field) throws Exception;
}
